﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel=Microsoft.Office.Interop.Excel;

namespace ExCopy
{
    class Program
    {
        static void Main(string[] args)
        {
            Excel.Application xApp = new Excel.Application(); ;
 
            //ExCopy "c:\a.xlsx" "Sheet1" "c:\b.xlsx" "Shee1"
            if (args.Length < 3)
            {
                Console.WriteLine("Invalid Arguments");
                string helpString = "Valid Syntax\n"
                                  + "ExCopy sourceExcelFile sourceSheetName DestinationFileName [showExcel] \n"
                                  + "showExcel : use yes to show Excel AUI";
                Console.WriteLine(helpString);
                return;
            }

            string sourceFile, destFile, sourceRange, showExcel;
            sourceFile=args[0];
            sourceRange = args[1];
            destFile= args[2];
            showExcel = args[3];

            try
            {
               xApp = new Excel.Application();
                xApp.Visible = false;
                Excel.Workbook xSourceBook = xApp.Workbooks.Open(sourceFile);
                Excel.Workbook xDestBook = xApp.Workbooks.Open(destFile);

                Excel.Worksheet xSourceSheet = xSourceBook.Worksheets.get_Item(sourceRange);

                //xSourceSheet = xSourceBook.Worksheets.get_Item(sourceRange);
                //if (xDestBook.Worksheets.get_Item(sourceRange) != null)
                //xDestBook.Worksheets[sourceRange].Delete();

                foreach (Excel.Worksheet sheet in xDestBook.Worksheets)
                {
                    if (sheet.Name.Equals(sourceRange))
                    {
                        xApp.DisplayAlerts = false;
                        ((Excel.Worksheet)xDestBook.Worksheets[sourceRange]).Delete();
                        xApp.DisplayAlerts = true;
                    }

                }



                xSourceSheet.Copy(Before: xDestBook.Worksheets[1]);

                

                if (showExcel.ToLower() == "yes")
                {
                    xApp.Visible = true;
                    xDestBook.Save();
                }
                else
                {
                    xSourceBook.Close();
                    xDestBook.Save();
                    xDestBook.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error:= " + ex.Message);
                Console.WriteLine("Source:= " + ex.Source);
                xApp.Workbooks.Close();
            }
            finally
            {
                
            }
        }
    }
}
